package com.kfm.loginIp.controller;

import com.kfm.loginIp.service.UserService;
import com.kfm.loginIp.util.*;
import com.wf.captcha.utils.CaptchaUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;

/**
 * @author Aurora雪
 */
@RestController
public class UserController {
    @Autowired
    private UserService userService;
    //redis是内存数据库，可以存储大量数据，可以做分布式缓存，可以做分布式锁
    @Autowired
    private StringRedisTemplate redisTemplate;//redis模板

    /**
     * 注册页面
     * @return
     */
    @GetMapping("/register")
    public ModelAndView register(){
        return new ModelAndView("/register");
    }

    /**
     * 用户名或邮箱注册
     * @param username
     * @param password
     * @param rePassword
     * @return
     */
    @PostMapping("/register")
    public RespUtil register(String username, String password, String rePassword) {
        String privateKey = KeyStore.getInstance().getPrivateKey();//获取私钥
        String username1 = RSAUtil.decryptWithPrivateKeyBlock(username, privateKey);//解密用户名
        String password1 = RSAUtil.decryptWithPrivateKeyBlock(password, privateKey);//解密密码
        String rePassword1 = RSAUtil.decryptWithPrivateKeyBlock(rePassword, privateKey);//解密确认密码
        int register = userService.register(username1, password1, rePassword1);

        if (register == 1) {
            return RespUtil.ok("util/registerSuccess");
        } else {
            return RespUtil.error(500, "注册失败,请重新注册！", null);
        }
    }

    /**
     * 获取验证码
     * @param phone
     * @return
     */
    @PostMapping("/getVerifyVerificationCode")
    public RespUtil getVerifyVerificationCode(String phone) {
        if (phone!=null){
            TencentSmsUtil tencentSmsUtil = new TencentSmsUtil(redisTemplate);//实例化工具类
            String verificationCode = TencentSmsUtil.generateVerificationCode();//生成验证码
            //发送验证码
            boolean registerVerificationCode = tencentSmsUtil.registerVerificationCode(phone, verificationCode);
            //模拟发送验证码
//            boolean registerVerificationCode = tencentSmsUtil.sendSms(phone,verificationCode);
            if (registerVerificationCode){
                return RespUtil.ok(verificationCode);
            }else {
                return RespUtil.error(501, "验证码发送失败，请重试！", null);
            }
        }else {
            return RespUtil.error(500, "手机号码不能为空！", null);
        }
    }

    /**
     * 手机号注册
     * @param phone
     * @param verCode
     * @param password
     * @param rePassword
     * @return
     */
    @PostMapping("/phoneRegister")
    public RespUtil phoneRegister(String phone,String verCode, String password, String rePassword) {
        TencentSmsUtil tencentSmsUtil = new TencentSmsUtil(redisTemplate);//实例化工具类
        boolean inputVerifyVerificationCode = tencentSmsUtil.inputVerifyVerificationCode(phone, verCode);
        if (inputVerifyVerificationCode){
            String privateKey = KeyStore.getInstance().getPrivateKey();//获取私钥
            //用私钥解密
            String password1 = RSAUtil.decryptWithPrivateKeyBlock(password, privateKey);
            String rePassword1 = RSAUtil.decryptWithPrivateKeyBlock(rePassword, privateKey);
            int register = userService.phoneRegister(phone, password1, rePassword1);
            if (register == 1) {
                return RespUtil.ok("util/registerSuccess");
            } else {
                return RespUtil.error(500, "注册失败,请重新注册！", null);
            }
        }else {
            return RespUtil.error(501, "验证码错误，请重新输入！", null);
        }
    }

    /**
     * 注册成功页面
     * @return
     */
    @GetMapping("util/registerSuccess")
    public ModelAndView registerSuccess(){
        return new ModelAndView("util/registerSuccess");
    }

    /**
     * 注册失败页面
     * @return
     */
    @GetMapping("util/500")
    public ModelAndView registerError(){
        return new ModelAndView("util/500");
    }

    /**
     * 检查用户名是否存在
     * @param username
     * @return
     */
    @PostMapping("/checkUsername")
    public String checkUsername(@RequestParam("username") String username) {
        // 查询数据库，检查用户名是否存在
        if (userService.checkUsername(username)) {
            // 如果存在，返回 "exists"
            return "exists";
        }else {
            // 如果不存在，返回 "not exists"
            return "not exists";
        }
    }

    /**
     * 检查手机号是否存在
     * @param phone
     * @return
     */
    @PostMapping("/checkPhone")
    public String checkPhone(@RequestParam("phone") String phone) {
        // 查询数据库，检查用户名是否存在
        if (userService.checkPhone(phone)) {
            // 如果存在，返回 "exists"
            return "exists";
        }else {
            // 如果不存在，返回 "not exists"
            return "not exists";
        }
    }

    /**
     * 检查邮箱或手机号是否存在
     * @param input
     * @return
     */
    @PostMapping("/checkEmailOrPhone")
    public String checkEmailOrPhone(@RequestParam("input") String input) {
        // 查询数据库，检查用户名是否存在
        if (userService.checkEmailOrPhone(input)) {
            // 如果存在，返回 "exists"
            return "exists";
        }else {
            // 如果不存在，返回 "not exists"
            return "not exists";
        }
    }

    /**
     * 找回密码页面
     * @return
     */
    @GetMapping("/retrieve")
    public ModelAndView retrieve() {
        return new ModelAndView("user/retrieve");
    }

    /**
     * 处理找回密码页面
     * @param input
     * @param captcha
     * @param request
     * @return
     */
    @PostMapping("/retrieve")
    public RespUtil handleRetrieve(String input, String captcha, HttpServletRequest request,HttpSession session) {
        if (!CaptchaUtil.ver(captcha, request)) {//验证码错误
            // 清除验证码
            CaptchaUtil.clear(request);
            // 重定向到找回密码页面
            return RespUtil.error(201, "验证码错误，请重新输入！", null);
        }
        // 清除验证码
        CaptchaUtil.clear(request);
        String phoneReg = "^1[3-9]\\d{9}$";
        String emailReg = "^\\w+([-+.']\\w+)*@\\w+([-.]\\w+)*\\.\\w+([-.]\\w+)*$";
        if (input.matches(phoneReg)) {//手机号
            TencentSmsUtil tencentSmsUtil = new TencentSmsUtil(redisTemplate);//实例化工具类
            String verificationCode = TencentSmsUtil.generateVerificationCode();//生成验证码
            //发送验证码
            boolean retrieveVerificationCode = tencentSmsUtil.retrieveVerificationCode(phoneReg, verificationCode);
            //模拟发送验证码
//            boolean retrieveVerificationCode = tencentSmsUtil.sendSms(input,verificationCode);
            if (retrieveVerificationCode){
                session.setAttribute("phone", input);
                return RespUtil.ok("user/phoneRetrieve");
            }else {
                return RespUtil.error(501, "验证码发送失败，请重试！", null);
            }
        } else if (input.matches(emailReg)) {//邮箱,发送邮箱链接
            boolean mailSend = MailUtil.endEmail(input);
            if (mailSend){
                session.setAttribute("email", input);
                return RespUtil.ok("util/emailSuccess");
            }else {
                return RespUtil.error(501, "邮箱发送失败，请重试！", null);
            }
        }
        return RespUtil.error(500, "手机号码不能为空！", null);
    }

    /**
     * 找回密码成功页面
     * @return
     */
    @GetMapping("util/emailSuccess")
    public ModelAndView success(HttpSession session) {
        ModelAndView modelAndView = new ModelAndView("util/emailSuccess");
        String email = (String) session.getAttribute("email");
        modelAndView.addObject("email", email);
        return modelAndView;
    }

    /**
     *电话找回密码页面
     * @return
     */
    @GetMapping("user/phoneRetrieve")
    public ModelAndView phoneRetrieve(HttpSession session) {
        ModelAndView modelAndView = new ModelAndView("user/phoneRetrieve");
        String phone = (String) session.getAttribute("phone");
        modelAndView.addObject("phone", phone);
        return modelAndView;
    }

    /**
     * 处理电话找回密码页面
     * @param verificationCode
     * @param password
     * @param rePassword
     * @param phone
     * @return
     */
    @PostMapping("/phoneRetrieve")
    public RespUtil handlePhoneRetrieve(String verificationCode, String password, String rePassword, String phone) {
        if (verificationCode == null) {
            return RespUtil.error(500, "验证码不能为空！", null);
        }else {
            TencentSmsUtil tencentSmsUtil = new TencentSmsUtil(redisTemplate);//实例化工具类
            //验证验证码
            String phone1 = phone.substring(3);
            boolean retrieveVerifyVerificationCode = tencentSmsUtil.retrieveVerifyVerificationCode(phone1, verificationCode);
            if (retrieveVerifyVerificationCode) {
                //解码
                String privateKey = KeyStore.getInstance().getPrivateKey();//获取私钥
                //用私钥解密
                String password1 = RSAUtil.decryptWithPrivateKeyBlock(password, privateKey);
                String rePassword1 = RSAUtil.decryptWithPrivateKeyBlock(rePassword, privateKey);
                if (password1.equals(rePassword1)) {
                    //修改密码
                    if (userService.updatePassword(phone1, password1) == 1){
                        return RespUtil.ok("util/phoneSuccess");
                    }else {
                        return RespUtil.error(500, "修改密码失败！", null);
                    }
                }else {
                    return RespUtil.error(500, "两次输入的密码不一致！", null);
                }
            }else {
                return RespUtil.error(501, "验证码错误，请重新输入！", null);
            }
        }
    }

    /**
     * 找回密码成功页面
     * @return
     */
    @GetMapping("/util/phoneSuccess")
    public ModelAndView phoneSuccess() {
        return new ModelAndView("util/phoneSuccess");
    }

    /**
     * 邮箱找回密码页面
     * @return
     */
    @GetMapping("user/emailRetrieve")
    public ModelAndView emailRetrieve(String email) {
        ModelAndView modelAndView = new ModelAndView("user/emailRetrieve");
        System.out.println(email);
        modelAndView.addObject("email", email);
        return modelAndView;
    }

    /**
     * 处理邮箱找回密码页面
     * @param password
     * @param rePassword
     * @param email
     * @return
     */
    @PostMapping("/emailRetrieve")
    public RespUtil handleEmailRetrieve(String password, String rePassword ,String email) {
        if (password == null) {
            return RespUtil.error(500, "密码不能为空！", null);
        }else {
            //解码
            String privateKey = KeyStore.getInstance().getPrivateKey();//获取私钥
            //用私钥解密
            String password1 = RSAUtil.decryptWithPrivateKeyBlock(password, privateKey);
            String rePassword1 = RSAUtil.decryptWithPrivateKeyBlock(rePassword, privateKey);
            if (password1.equals(rePassword1)) {
                //修改密码
                if (userService.updateEmail(email, password1) == 1){
                    return RespUtil.ok("util/phoneSuccess");
                }else {
                    return RespUtil.error(500, "修改密码失败！", null);
                }
            }else {
                return RespUtil.error(501, "两次输入的密码不一致！", null);
            }
        }
    }


    /**
     * 退出登录
     * @return
     */
    @GetMapping("/logout")
    public ModelAndView logout(HttpServletRequest request){
        request.getSession().invalidate(); // 清除Session中的用户信息
        return new ModelAndView("/login");
    }
}
